#include "stockcheck.h"
#include "ui_stockcheck.h"
#include <QMessageBox>
#include <QJsonArray>

StockCheckWindow::StockCheckWindow(QWidget *parent)
    : QWidget(parent)
    , stockcheckwindowUi(new Ui::StockCheckWindow)
    , networkManager(new NetworkManager(this))
{
    stockcheckwindowUi->setupUi(this);

    connect(networkManager, &NetworkManager::checkStockResponseReceived, this, &StockCheckWindow::handleCheckStockResponse);
}

StockCheckWindow::~StockCheckWindow()
{
    delete stockcheckwindowUi;
}

void StockCheckWindow::on_queryButton_clicked()
{
    networkManager->checkStock();
}

void StockCheckWindow::handleCheckStockResponse(const QJsonObject &response)
{
    int code = response.value("code").toInt();
    QString desc = response.value("desc").toString();

    if (code == 200) {
        QString dataString = response.value("data").toString();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(dataString.toUtf8());
        if (!jsonDoc.isArray()) {
            stockcheckwindowUi->resultlabel->setText("库存预警查询成功，目前没有商品存在库存预警！");
            return;
        }
        stockcheckwindowUi->resultlabel->setText("库存预警查询成功，以下商品存在库存预警！");

        QJsonArray data = jsonDoc.array();

        stockcheckwindowUi->resultTable->setRowCount(0);

        for (int i = 0; i < data.size(); ++i) {
            QJsonObject record = data[i].toObject();

            int row = stockcheckwindowUi->resultTable->rowCount();
            stockcheckwindowUi->resultTable->insertRow(row);
            stockcheckwindowUi->resultTable->setItem(row, 0, new QTableWidgetItem(record.value("name").toString()));
            stockcheckwindowUi->resultTable->setItem(row, 1, new QTableWidgetItem(record.value("supplier").toString()));
            stockcheckwindowUi->resultTable->setItem(row, 2, new QTableWidgetItem(QString::number(record.value("price").toDouble())));
            stockcheckwindowUi->resultTable->setItem(row, 3, new QTableWidgetItem(QString::number(record.value("stock").toInt())));
            stockcheckwindowUi->resultTable->setItem(row, 4, new QTableWidgetItem(QString::number(record.value("threshold").toInt())));
        }
    } else {
        stockcheckwindowUi->resultlabel->setText("库存查询失败：" + desc);
    }
}
